<?php

use Illuminate\Database\Capsule\Manager as DB;

abstract class CommonController extends CoreController
{
    protected $table;
    protected $model;
    protected $primaryKey= "id";
    protected $condition = [];
    protected $condition_in = [];
    protected $search = [];


    /**
     * @name 获取数据列表@基类
     * @param bool $returnData
     * @return array
     */
    public function getAction($returnData = FALSE)
    {
        $query = $this->model ? (new $this->model) : DB::table($this->table);
        if (!empty($this->search)) {
            $query = $query->where(function ($query) {
                foreach ($this->search as $v) {
                    if (isset($v[3]) && strtolower($v[3]) == 'or') {
                        $query = $query->orWhere([$v]);
                    } else {
                        $query = $query->where([$v]);
                    }
                }
            });
        }
        if (!empty($this->condition)) {
            $query = $query->where($this->condition);
        }
        if (!empty($this->condition_in)) {
            foreach ($this->condition_in as $k => $v) {
                $query = $query->whereIn($v[0], $v[1]);
            }
        }
        $total = $query->count();
        $sort  = $this->get('sort', 'sortorder');
        $order = $this->get('order', 'desc');
        $query = $query->orderBy($sort, $order);
        $page  = $this->get('page');
        if (!empty($page)) {
            $limit  = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $query  = $query->offset($offset)->limit($limit);
        }
        $rows = $query->get();
        if ($returnData) {
            return ['total' => $total, 'rows' => $rows];
        } else {
            json(['total' => $total, 'rows' => $rows]);
        }
    }

    /**
     * @name 添加数据@基类
     */
    public function addAction()
    {
        if($this->isPost()) {
            do {
                $rows = $this->postData;
                $rows['created_at'] = date('Y-m-d H:i:s');
                unset($rows[$this->primaryKey], $rows['updated_at']);
                $this->cleanColumn($rows);
                if ($insert_id = DB::table($this->table)->insertGetId($rows)) {
                    $result = [
                        'ret' => 0,
                        'msg' => '操作成功',
                        'data' => $insert_id,
                    ];
                } else {
                    $result = [
                        'ret' => 3,
                        'msg' => '数据插入失败',
                    ];
                }
            } while (FALSE);
            json($result);
        }else{
            $this->_view->assign('dataset', json_encode($this->getTableColumn($this->table)));
            $this->_view->display( strtolower($this->controller) . '/edit.html');
        }
    }

    /**
     * @name 添加数据，返回新增ID
     * @return int
     */
    protected function insertGetId()
    {
        $rows               = $this->postData;
        $rows['created_at'] = date('Y-m-d H:i:s');
        $this->cleanColumn($rows);
        return DB::table($this->table)->insertGetId($rows);
    }

    /**
     * @name 编辑数据@基类
     * @param bool $returnData
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     * @throws Exception
     */
    public function editAction()
    {
        if($this->isPost()) {
            do {
                $rows = $this->postData;
                if (!isset($rows['id']) && isset($rows['dataset']) && is_array($rows['dataset'])) {
                    $rows = $rows['dataset'];
                }
                $roles = [
                    'id' => ['role' => "required|exists:{$this->table}.{$this->primaryKey}", 'func' => 'isInt', 'msg' => '主键'],
                ];
                Validate::check($rows, $roles);
                $rows['updated_at'] = date('Y-m-d H:i:s');
                unset($rows['created_at']);
                $this->cleanColumn($rows);
                if (DB::table($this->table)->where($this->primaryKey, $rows['id'])->update($rows) !== FALSE) {
                    $result = [
                        'ret' => 0,
                        'msg' => '操作成功',
                    ];
                } else {
                    $result = [
                        'ret' => 3,
                        'msg' => '更新失败',
                    ];
                }
            } while (FALSE);
            json($result);
        }else{
            $id	= $this->get('id', 0);
            if(DB::table($this->table)->where($this->primaryKey,'=',$id)->doesntExist()){
                throw new Exception("记录不存在");
            }
            $this->_view->assign('dataset', json_encode(DB::table($this->table)->where($this->primaryKey,'=',$id)->first()));
            $this->_view->display( strtolower($this->controller) . '/edit.html');
        }
    }

    /**
     * @name 清除多余字段
     */
    protected function cleanColumn(&$rows)
    {
        $columns = [];
        foreach (DB::select("SHOW COLUMNS FROM `{$this->config->database->prefix}{$this->table}`") as $v) {
            $columns[] = $v->Field;
        }
        foreach ($rows as $k => $v) {
            if (!in_array($k, $columns)) {
                unset($rows[$k]);
            }
        }
    }

    /**
     * @name 返回表的字段
     */
    protected function getTableColumn($table)
    {
        $columns = [];
        foreach (DB::select("SHOW COLUMNS FROM `{$this->config->database->prefix}{$table}`") as $v) {
            $columns[$v->Field] = '';
        }
        return $columns;
    }

    /**
     * @name 查看详情@基类
     * @param bool $returnData
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     */
    public function viewAction($returnData = FALSE)
    {
        $id = $this->get('id', 0);
        if (DB::table($this->table)->where($this->primaryKey, '=', $id)->doesntExist()) {
            ret(1, '记录不存在');
        }
        $query   = $this->model ? (new $this->model) : DB::table($this->table);
        $dataset = $query->where($this->primaryKey, '=', $id)->first();
        if ($returnData) {
            return $dataset;
        } else {
            ret(0, '记录详情', $dataset);
        }
    }

    /**
     * @name 删除数据@基类
     */
    public function deleteAction()
    {
        do {
            $id = $this->get('id', []);
            if (empty($id)) {
                $result = [
                    'ret' => 2,
                    'msg' => '参数为空',
                ];
                break;
            }
            if (is_array($id)) {
                if (DB::table($this->table)->whereIn($this->primaryKey, $id)->delete()) {
                    $result = [
                        'ret' => 0,
                        'msg' => '操作成功',
                    ];
                    break;
                }
            } elseif (is_numeric($id)) {
                if (DB::table($this->table)->where($this->primaryKey, '=', $id)->doesntExist()) {
                    $result = [
                        'ret' => 4,
                        'msg' => '记录不存在',
                    ];
                    break;
                }
                if (DB::table($this->table)->where($this->primaryKey, '=', $id)->delete()) {
                    $result = [
                        'ret' => 0,
                        'msg' => '操作成功',
                    ];
                    break;
                }
            }
            $result = [
                'ret' => '5',
                'msg' => '删除失败',

            ];
        } while (FALSE);
        json($result);
    }
}
